<?php
declare(strict_types = 1);
namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;
use app\common\lib\sms\SmsBase;

class AliSms implements SmsBase
{
    // 返回值为bool类型
    public static function sendCode(string $phone, int $code) : bool
    {
        // 判断手机号和验证码是否为空
        if (empty($phone) || empty($code)) {
            # code...
            return false;
        }
        //
        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
// use STS Token
// AlibabaCloud::stsClient('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
                        ->regionId('cn-qingdao')
                        ->asDefaultClient();

        // $templateParem = [
        //     'code' => $code,
        // ];
        $templateParem = [
            'code' => $code
        ];
        try {
            $result = AlibabaCloud::rpc()
                          ->product('Dysmsapi')
                          // ->scheme('https') // https | http
                          ->version('2017-05-25')
                          ->action('SendSms')
                          ->method('POST')
                          ->host(config('aliyun.host'))
                          ->options([
                                        'query' => [
                                            'Regioned' => config('aliyun.regioned_id'),
                                            'SignName' => config('aliyun.sign_name'),
                                            'TemplateCode' => config('aliyun.template_code'),
                                            'PhoneNumbers' => $phone,
                                            'TemplateParem' => json_encode($templateParem),
                                        ],
                                    ])
                          ->request();
            // print_r($result->toArray());
            Log::info("alisms-sendCode-result-{$phone}", $result->toArray());
        } catch (ClientException $e) {
            // 写入日志
            Log::error('alisms-sendCode-ClientException', $e->getErrorMessage());
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            Log::error('alisms-sendCode-ServerException', $e->getErrorMessage());
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        }
        // 判断$result中的值是否为OK，OK代表发送成功！
        // if (isset($result['Code']) && $result['Code'] == 'OK') {
        //     # code...
        //     return true;
        // }
        return true;
    }
}
